🔶章節:
🔹[開頭]
🔹[什麼是迴圈]
🔹[for 迴圈 - 介紹&語法]
🔹[for 迴圈 - 實作]
🔹[for 迴圈 - 適用情境]
🔹[while 迴圈 - 介紹&語法]
🔹[while 迴圈 - 實作]
🔹[while 迴圈 - 適用情境]
🔹[do...while 迴圈 - 介紹&語法]
🔹[do...while 迴圈 - 實作]
🔹[do...while 迴圈 - 適用情境]
🔹[foreach 迴圈 - 介紹&語法]
🔹[foreach 迴圈 - 實作]
🔹[foreach 迴圈 - 適用情境]
🔹[使用迴圈即不使用迴圈的差異]
🔹[迴圈的優點]
🔹[總結]
(影片內容豐富)如果影片中不清楚,需要補充的地方我會再添加到這邊~
👆教學中的[練習]程式碼一併附上,影片中會有每組的講解,說明更清楚👆
for (初始化; 條件; 遞增或遞減) {
// 在每次迭代中執行的程式碼
}
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}
echo "總和:$sum";
for ($i = 1; $i <= 9; $i++) {
for ($j = 1; $j <= 9; $j++) {
$num = $i * $j;
echo "$i x $j = $num<br>";
}
echo "<br>";
}
for ($i = 10; $i >= 1; $i--) {
echo "$i...";
sleep(1); // 等待 1 秒
}
echo "發射!";
while (條件) {
// 在條件為真時執行的程式碼
}
$sum = 0;
$i = 1;
while ($i <= 10) {
$sum += $i;
$i++;
}
echo "總和:$sum";
$targetNumber = rand(1, 100); // 生成 1 到 100 的隨機數
$guess = null;
$attempts = 0;
while ($guess !== $targetNumber) {
$guess = rand(1, 100);
$attempts++;
echo "猜第 $attempts 次:$guess<br>";
if ($guess < $targetNumber) {
echo "太小了<br>";
} elseif ($guess > $targetNumber) {
echo "太大了<br>";
} else {
echo "猜對了!";
}
}
do {
// 要執行的程式碼
} while (條件);
$sum = 0;
$i = 1;
do {
$sum += $i;
$i++;
} while ($i <= 10);
echo "總和:$sum";
$number = 0;
do {
$number = readline("請輸入一個正整數:");
} while (!is_numeric($number) || $number <= 0);
echo "您輸入的數字是:$number";
foreach ($array as $element) {
// 要執行的程式碼,使用 $element
}
$colors = array("紅色", "綠色", "藍色");
foreach ($colors as $color) {
echo "顏色:$color<br>";
}
$studentScores = array(
"Ariana" => 85,
"Brian" => 92,
"Amy" => 78
);
foreach ($studentScores as $name => $score) {
echo "$name 的分數是 $score<br>";
}
$sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
echo "總和:$sum";
$sum = 0;
for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}
echo "總和:$sum";
$colors = array("紅色", "綠色", "藍色");
echo "顏色:$colors[0]<br>";
echo "顏色:$colors[1]<br>";
echo "顏色:$colors[2]<br>";
$colors = array("紅色", "綠色", "藍色");
foreach ($colors as $color) {
echo "顏色:$color<br>";
}